﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WizardBase;

using OrangePrj.Forms;

namespace OrangePrj
{
    public partial class CreateNewProjectWizard : Form
    {
        #region Поля и свойства

        private User currentUser;
        private Project project;
        private Work selectedWork;
        private List<Work> selectedWorks;
        private List<WorkType> workTypeList;
        private bool isCorrect = false;

        public Project Project
        {
            get
            {
                return project;
            }
        }

        #endregion

        #region Конструкторы

        public CreateNewProjectWizard() : this (new User())
        {
            
        }
        public CreateNewProjectWizard(User user)
        {
            InitializeComponent();
            this.currentUser = user;
            workTypeList = new List<WorkType>();
            workTypeList.Add(WorkType.Простая);
            workTypeList.Add(WorkType.Искл_ИЛИ);
            workTypeList.Add(WorkType.ИЛИ);

            project = new Project();
            dgWorkList.DataSource = project.worklist;

#if DEBUG
            project = new Project("Test", "Test Description", currentUser);
            Work w1 = new Work("Работа 1", "Описание 1");
            Work w2 = new Work("Работа 2", "Описание 2");
            Work w3 = new Work("Работа 3", "Описание 3");
            Work w4 = new Work("Работа 4", "Описание 4");
            Work w5 = new Work("Работа 5", "Описание 5");
            Work w6 = new Work("Работа 6", "Описание 6");

            project.worklist.Add(w1);
            project.worklist.Add(w2);
            project.worklist.Add(w3);
            project.worklist.Add(w4);
            project.worklist.Add(w5);
            project.worklist.Add(w6);

            project.worklist[1].SetDependence(w1);
            project.worklist[2].SetDependence(w2);
            project.worklist[4].SetDependence(w3);
            project.worklist[4].SetDependence(w4);
            RefreshProjectInfo();
            RefreshListView();
#endif
   
        }

        #endregion

        #region Приватные методы

        /// <summary>
        /// Обновляет все списки с работами
        /// </summary>
        private void RefreshListView()
        {
            RefreshWorkListView();
            RefreshWorkDepListView();
            RefresWorkDataGrid();
        }

        #endregion

        #region Обработчик основных кнопок Мастера
        private void Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void wizardControl1_FinishButtonClick(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        /// <summary>
        /// Обрабатывает нажатие клавиши Next. 
        /// </summary>
        private void wizardControl1_NextButtonClick(object sender, EventArgs e)
        {
            if ((wizardControl1.CurrentStepIndex == 0 && project == null) || (wizardControl1.CurrentStepIndex == 4 && !isCorrect))
            {
                wizardControl1.NextButtonEnabled = false;
            }
            errorWorkLabel.Visible = false;
            EditWorkButton.Enabled = false;
            DeleteWorkButton.Enabled = false;

            lblWorkDepError.Visible = false;
        }

        /// <summary>
        /// Обрабатывает нажатие клавиши Back.
        /// </summary>
        private void wizardControl1_BackButtonClick(object sender, EventArgs e)
        {
            wizardControl1.NextButtonEnabled = true;
            errorWorkLabel.Visible = false;
            EditWorkButton.Enabled = false;
            DeleteWorkButton.Enabled = false;

            lblWorkDepError.Visible = false;
        }
        #endregion

        #region Шаг 1. Создание проекта.

        private void OpenProjectButton_Click(object sender, EventArgs e)
        {
            String errorMessage;
            Project tempProject;
            if ((tempProject = FileReader.Open(currentUser, out errorMessage)) != null)
            {
                project = tempProject;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show(errorMessage, "Ошибка при чтении из файла", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CreateProjectButton_Click(object sender, EventArgs e)
        {
            FormNewPrj newProjectDialog = new FormNewPrj();
            newProjectDialog.ShowDialog();
            if(newProjectDialog.DialogResult == DialogResult.OK)
            {
                this.project = new Project(newProjectDialog.ProjectName, newProjectDialog.Description, currentUser);
                RefreshProjectInfo();
                RefreshListView();
            }
        }

        /// <summary>
        /// Отображает всю информацию о проекте в соответсующих полях Мастера
        /// </summary>
        /// <returns>Состояние отображения</returns>
        private bool RefreshProjectInfo()
        {
            if (project == null)
            {
                return false;
            }

            wizardControl1.NextButtonEnabled = true;
            this.projectTextLabel.Text = project.Name;
            this.projectLabel.Visible = true;
            this.projectTextLabel.Visible = true;
            if (project.Descr.Length != 0)
            {
                this.DescriptionTextLabel.Text = project.Descr;
                this.descriptionLabel.Visible = true;
                this.DescriptionTextLabel.Visible = true;
                DescriptionTextLabel.Height = DescriptionTextLabel.GetPreferredSize(new Size(DescriptionTextLabel.Width, 0)).Height;
            } else
            {
                this.descriptionLabel.Visible = false;
                this.DescriptionTextLabel.Visible = false;
            }
            return true;
        }
        #endregion

        #region Шаг 2. Редактирование списка работ.

        private void AddWorkButton_Click(object sender, EventArgs e)
        {
            errorWorkLabel.Visible = false;
            FormAddWork addWorkDialog = new FormAddWork();
            addWorkDialog.ShowDialog();
            if (addWorkDialog.DialogResult == DialogResult.OK)
            {
                project.worklist.Add(addWorkDialog.w);
                RefreshListView();
            }
        }

        /// <summary>
        /// Позволяет редактировать выбранную работу.
        /// </summary>
        private void EditWorkButton_Click(object sender, EventArgs e)
        {
            if (workListView.SelectedItems.Count == 0)
            {
                errorWorkLabel.Visible = true;
                return;
            }
            errorWorkLabel.Visible = false;

            string name = workListView.SelectedItems[0].Text;
            Work work = project.worklist.getWorkByName(name);
            FormAddWork editWorkForm = new FormAddWork(work);
            editWorkForm.ShowDialog();
            if (editWorkForm.DialogResult == DialogResult.OK)
            {
                work = (Work)editWorkForm.w.Clone();
            }

            RefreshListView();

        }

        /// <summary>
        /// Удаляет выбранную работу
        /// </summary>
        private void DeleteWorkButton_Click(object sender, EventArgs e)
        {
            if (workListView.SelectedItems.Count == 0)
            {
                errorWorkLabel.Visible = true;
                return;
            }

            errorWorkLabel.Visible = false;

            project.worklist.DeleteWork(workListView.SelectedItems[0].Text);

            RefreshListView();
        }

        /// <summary>
        /// Отображает список работ в ListView
        /// </summary>
        private void RefreshWorkListView()
        {
            workListView.Items.Clear();
            foreach (Work work in project.worklist)
            {
                WorkItem workItem = new WorkItem(work);
                workListView.Items.Add(workItem);
            }
            if (workListView.SelectedItems.Count == 0)
            {
                EditWorkButton.Enabled = false;
                DeleteWorkButton.Enabled = false;
            } else
            {
                EditWorkButton.Enabled = true;
                DeleteWorkButton.Enabled = true;
            }
        }

        private void workListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (workListView.SelectedItems.Count == 0)
            {
                EditWorkButton.Enabled = false;
                DeleteWorkButton.Enabled = false;
            } else
            {
                EditWorkButton.Enabled = true;
                DeleteWorkButton.Enabled = true;
            }
        }

        #endregion

        #region Шаг 3. Редактирование зависимостей работ.

        /// <summary>
        /// Отображает работы в списке с зависимостями
        /// </summary>
        private void RefreshWorkDepListView()
        {
            workDepListView.Items.Clear();
            foreach (Work work in project.worklist)
            {
                WorkItem workItem = new WorkItem(work);
                workDepListView.Items.Add(workItem);
            }
        }

        private void btnSetDependences_Click(object sender, EventArgs e)
        {
            FormSetDependences frmSetDependences;

            if (workDepListView.SelectedItems.Count == 0)
            {
                frmSetDependences = new FormSetDependences(project, project.worklist[0]);
            }
            else
            {
                frmSetDependences = new FormSetDependences(project, project.worklist.getWorkByName(workDepListView.SelectedItems[0].Text));
                workDepListView.SelectedItems[0].Selected = false;
            }

            frmSetDependences.ShowDialog();
            if (frmSetDependences.DialogResult == DialogResult.OK)
            {
                project = frmSetDependences.project;
                RefreshListView();
            }
        }

        #endregion

        #region Шаг 4. Установка альтернатив.
        /// <summary>
        /// Обновляет список работ в дата гриде
        /// </summary>
        private void RefresWorkDataGrid()
        {
            dgWorkList.DataSource = project.worklist;
            //Type.DataSource = Enum.GetValues(typeof(WorkType));
            Type.DataSource = workTypeList;
            errorDataGridLabel.Visible = false;

            foreach(DataGridViewRow row in dgWorkList.Rows)
            {
                if ((WorkType)(row.Cells[2].Value) == WorkType.Простая)
                {
                    row.Cells[3].Value = 1;
                    row.Cells[3].ReadOnly = true;
                    row.Cells[3].Style.BackColor = Color.Gray;
                }
                else
                {
                    row.Cells[3].ReadOnly = false;
                    row.Cells[3].Style.BackColor = Color.White;
                }
            }

            string errorMessage;
            if ((errorMessage = project.checkWorkTypeXOR()) != "")
            {
                isCorrect = false;
                wizardControl1.NextButtonEnabled = false;
                errorDataGridLabel.Visible = true;
                errorDataGridLabel.Text = errorMessage;
            }
            else
            {
                isCorrect = true;
                wizardControl1.NextButtonEnabled = true;
                errorDataGridLabel.Visible = false;
            }
        }

        private void dgWorkList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                //Изменили тип работы
                if (e.ColumnIndex == 2)
                {
                    if ((WorkType)(dgWorkList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) == WorkType.Простая)
                    {
                        dgWorkList.Rows[e.RowIndex].Cells[3].Value = 1;
                        dgWorkList.Rows[e.RowIndex].Cells[3].ReadOnly = true;
                        dgWorkList.Rows[e.RowIndex].Cells[3].Style.BackColor = Color.Gray;
                    }
                    else
                    {
                        dgWorkList.Rows[e.RowIndex].Cells[3].ReadOnly = false;
                        dgWorkList.Rows[e.RowIndex].Cells[3].Style.BackColor = Color.White;
                    }
                }

                //Вероятность
                if (e.ColumnIndex == 3)
                {
                    object value = dgWorkList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    double result;
                    if (!double.TryParse(value.ToString(), out result))
                    {
                        dgWorkList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 1;
                        errorDataGridLabel.Text = "Вероятность должна быть больше 0 и меньше 1";
                        errorDataGridLabel.Visible = true;
                        return;
                    }
                    else
                    {
                        if (result <= 0 || result > 1)
                        {
                            dgWorkList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 1;
                            errorDataGridLabel.Text = "Вероятность должна быть больше 0 и меньше 1";
                            errorDataGridLabel.Visible = true;
                            return;
                        }

                        errorDataGridLabel.Visible = false;
                    }
                }

                string errorMessage;
                if ((errorMessage = project.checkWorkTypeXOR()) != "")
                {
                    isCorrect = false;
                    wizardControl1.NextButtonEnabled = false;
                    errorDataGridLabel.Visible = true;
                    errorDataGridLabel.Text = errorMessage;
                }
                else
                {
                    isCorrect = true;
                    wizardControl1.NextButtonEnabled = true;
                    errorDataGridLabel.Visible = false;
                }
            }
        }

        private void dgWorkList_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.Context == DataGridViewDataErrorContexts.Formatting)
            {
                if (e.ColumnIndex == 3)
                {
                    dgWorkList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 1;
                    errorDataGridLabel.Text = "Вероятность должна быть больше 0 и меньше 1";
                    errorDataGridLabel.Visible = true;
                }
            }
        }

        #endregion
    }
}
